package tencent

import (
	"context"
	"fmt"
	"github.com/ecodeclub/ekit"
	"github.com/ecodeclub/ekit/slice"
	tentSms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20190711"
	"jk-time/webook/internal/service/sms"
	"jk-time/webook/pkg/limiter"
)

type Service struct {
	appId     *string
	signature *string
	client    *tentSms.Client
	limiter   limiter.Limiter
}

func NewService(client *tentSms.Client, appId string, signName string) sms.Service {
	return &Service{
		client:    client,
		appId:     &appId,
		signature: &signName,
	}
}
func (s *Service) Send(ctx context.Context, tplId string, args []string, numbers ...string) error {
	req := tentSms.NewSendSmsRequest()
	req.SmsSdkAppid = s.appId
	req.Sign = s.signature
	req.TemplateID = ekit.ToPtr[string](tplId)
	req.PhoneNumberSet = s.toPtrSlice(args)

	req.TemplateParamSet = s.toPtrSlice(numbers)
	resp, err := s.client.SendSms(req)
	if err != nil {
		return err
	}

	for _, statusPtr := range resp.Response.SendStatusSet {
		if statusPtr == nil {
			continue
		}
		status := *statusPtr
		if status.Code == nil || *(status.Message) != "Ok" {
			return fmt.Errorf("发送短信失败 %s,%s", status.Code, status.Message)
		}
	}
	return nil
}
func (s *Service) toPtrSlice(data []string) []*string {
	return slice.Map[string, *string](data, func(idx int, src string) *string {
		return &src
	})
}

var _ sms.Service = &Service{}
